﻿
using System;
using System.Collections.Generic;
using System.Linq;
using WHLRDF.ORM;
using WHLRDF.Application.Model;
namespace WHLRDF.Application.BLL
{
    public class PageService : SerivceBase, IPageService
    {
        #region 属性
        public const string Page_No_Rule = "0002";
        #endregion
        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<PageEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(PageEntity.__IsDeleted, false);
            return this.Query<PageEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public PageEntity GetById(string id)
        {
            return this.GetById<PageEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(PageEntity entity, ref string strError)
        {
            if (ChkPageName(entity.PageId, entity.LocalName, entity.ParentId))
            {
                strError = "页面存在，请检查";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.PageId))
            {
                entity.PageId = SerialService.CreateSerialNo(Page_No_Rule, null, ref strError);
            }
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<PageEntity>(deleteKey);
            }
            return true;
        }
        public LigerGrid ForGrid(LigerGrid ligerGrid)
        {
            ICriterion criter = Expression.Eq(PageEntity.__IsDeleted, false);
            string localName = ligerGrid.GetValue(PageEntity.__LocalName);
            string routeUrl = ligerGrid.GetValue(PageEntity.__RouteUrl);
            if (!string.IsNullOrWhiteSpace(localName))
            {
                criter = Expression.And(Expression.Like(PageEntity.__LocalName, localName), criter);
            }
            if (!string.IsNullOrWhiteSpace(routeUrl))
            {
                criter = Expression.And(Expression.Like(PageEntity.__RouteUrl, routeUrl), criter);
            }
            return this.Query<PageEntity>(ligerGrid, criter);
        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 判断页面是否不存在
        /// </summary>
        /// <param name="UserId">用户id</param>
        /// <param name="userAccount">用户账户</param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool ChkPageName(string pageId, string pageName,string parentId)
        {
            ICriterion criter = Expression.And(
            Expression.NotEq(PageEntity._PrimaryKeyName, pageId),
            Expression.And(Expression.Eq(PageEntity.__ActionName, pageName),
              Expression.And(Expression.Eq(PageEntity.__ParentId, parentId),
             Expression.Eq(PageEntity.__IsDeleted, false)))
             );
            var entity = this.Query<PageEntity>(criter).FirstOrDefault();
            return entity != null;
        }
        public List<PageEntity> GetMenuTree()
        {
            ICriterion criter = Expression.Eq(PageEntity.__IsDeleted, false);
            var lstAll = this.Query<PageEntity>(criter);
          //  var lstActionAll = this.Query<PageActionEntity>(criter);
            var lstMenu = new List<PageEntity>();
            if (lstAll != null && lstAll.Count > 0)
            {
                foreach (var item in lstAll.Where(x=>string.IsNullOrWhiteSpace(x.ParentId)))
                {
                    lstMenu.Add(item);
                    GetChildTree(lstAll,item.PageId,"--", ref lstMenu);
                }
            }
            return lstMenu;
        }

        public void GetChildTree(List<PageEntity> lstAll,string parentid,string path,ref List<PageEntity> lstMenu)
        {
           
            if (lstAll != null && lstAll.Count > 0)
            {
               
                foreach (var item in lstAll.Where(x => x.ParentId == parentid))
                {
                    item.LocalName = path + item.LocalName;
                    lstMenu.Add(item);
                    GetChildTree(lstAll, item.PageId, path+ "--", ref lstMenu);
                }
            }
          
        }
        public List<PageEntity> GetChildTree( string parentid)
        {
            // PageActionService pageActionService = new PageActionService();
          
            ICriterion criter = Expression.And( Expression.Eq(PageEntity.__IsDeleted, false),!string.IsNullOrWhiteSpace(parentid)? Expression.Eq(PageEntity.__ParentId, parentid):Expression.IsNull(PageEntity.__ParentId) );
           var lstMenu =  this.Query<PageEntity>(criter);
           
            return lstMenu;

        }
        public List<PageEntity> GetChildTree(List<PageEntity> lstAll, string parentid,bool isMenu=true)
        {
            List<PageEntity> lstMenu = new List<PageEntity>();
   
            if (lstAll != null && lstAll.Count > 0)
            {
                lstMenu = lstAll.Where(x => x.ParentId == parentid&&x.IsMenu== isMenu).ToList();
                
            }
            return lstMenu;

        }
        /// <summary>
        /// 初始化菜单链接
        /// </summary>
        /// <param name="strError"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool InitBatchSave(List<PageEntity> entities, ref string strError)
        {
            if (entities != null)
            {
                ICriterion criter = Expression.Eq("1","1");
               var oldPage=  this.GetAll();
              
                oldPage.ForEach(x => {
                    var newpage = entities.Where(y => x.PageId == y.PageId).FirstOrDefault();
                    if (newpage != null)
                    {
                        newpage.LocalName = x.LocalName;
                        newpage.IsDeleted = x.IsDeleted;
                        newpage.State = EntityState.Update;
                        if (newpage.IsDeleted)
                        {
                            newpage.State = EntityState.Delete;
                        }

                    }
                    else
                    {
                        x.IsDeleted = true;
                        x.State = EntityState.Delete;
                        entities.Add(x);
                    }
                });
                using (var tran = this.Begin())
                {
                    try
                    {
                        this.BatchSave<PageEntity>(entities);
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        strError = ex.Message;
                        return false;
                    }
                }
                   
            }
            return true;
        }

        public bool InitMenu(List<SystemComponent> lstComponent, ref string strError)
        {
            var lstPages= SystemMenuHelper.InitMenu(lstComponent);
            return InitBatchSave(lstPages,ref strError);
        }
        #endregion

    }
}